'use strict'

const titbit = require('titbit');
const { cookie, session } = require('titbit-toolkit');
const app = new titbit({
    debug: true
})

app.use((new cookie()).mid())

// 一定要在cookie之后，session是基于cookie的
//cookie保存的是session的用户名，可以在cookie里设置session的值
app.use((new session()).mid())

//分组。用空间换时间
app.use(async (c, next) => {
    console.log('just for home');
    await next();
}, { group: 'home' });

app.get('/', async c => {
    c.res.body = 'success';

    // },'@home')
    // 或者添加参数
}, { name: '首页', group: 'home' })

app.get('/cookie', async c => {
    c.res.body = c.headers['cookie'] || '还没设置cookie'
})

app.get('/login', async c => {
    c.res.body = `<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
            <form action="/login" method="post">
                <input type="text" name="username">
                <input type="password" name="passwd">
                <input type="submit" value="Login">
            </form>
        </body>
        </html>`
})

app.post('/login', async c => {

    console.log(c.body)
    c.res.body = c.body
    let { username, passwd } = c.body
    if (username === 'testuser' && passwd === '123456') {
        c.setSession('is_login', true)
        //登录成功就转到首页
        c.status(301)
        c.setHeader('Location', '/')
    } else {
        c.status(301)
        c.setHeader('Location', '/login')
    }
})

app.run(8934);